function res = features(input, type, param)
% FEATURES generate various histograms.
% Usage :
%   RES = FEATURES(INPUT, TYPE[, PARAM])
%   This function generates histogram of images specified in INPUT.
%
% Input :
%   INPUT is a matrix of image coef or a path to MAT files.
%   TYPE and PARAM is one of the following values:
%     'hist' : 1D histogram feature. Its range is [-PARAM:PARAM]. The
%        default value for PARAM is 10.
%     'markov' : Directional Difference Markov Feature. Its range is
%        [-PARAM:PARAM, -PARAM:PARAM]. The default value for PARAM is 4.
%
% Output :
%   RES is M*N matrix, where N is the number of features and M is the
%   number of samples.
%

if nargin < 3
    switch type
        case 'hist'
            param = 10;
        case 'markov'
            param = 4;
        otherwise
            error('Unsupported value of TYPE.');
    end
end
if (~isfloat(param)) || (param <= 0)
    error('Invalid value of PARAM.');
end
switch type
    case 'hist'
        N = 2*param + 1;
    case 'markov'
        N = 4*(2*param + 1)^2;
end
if ischar(input)
    inlist = dir([input,'/*.mat']);
    M = size(inlist, 1);
    res = zeros(M, N);
    count = 0;
    for i = 1:M
        if (inlist(i).isdir ~= 0) || (inlist(i).bytes <= 0)
            continue;
        end
        name = inlist(i).name;
        p = load([input,'/',name], 'coef');
        if ~isfield(p,'coef')
            continue;
        end
        count = count + 1;
        res(count,:) = hist_proc(p.coef, type, param);

        fprintf(1, 'Processed %s\n', name);
    end
    res = res(1:count,:);
    outfile = sprintf('%s/%s_%d.mat', input, type, param);
    save(outfile, 'res');
else
    res = hist_proc(input, type, param);
end
end

function h = hist_proc(coef, type, param)
    switch type
        case 'hist'
            h = generateHist(coef, param);
        case 'markov'
            h = generateDiff2DHist(coef, param);
    end
end
